<?php

class Products extends CActiveRecord
{
        public $orderID;//ivan
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	public function tableName()
	{
		return Shop::module()->productsTable;
	}

	public function beforeValidate() {
		if(Yii::app()->language == 'de')
			$this->price = str_replace(',', '.', $this->price);
		
		return parent::beforeValidate();
	}

	public function rules()
	{
		return array(
			array('title, phone, municipality_id, county_id, category_id', 'required'),
			array('product_id, category_id ,municipality_id, county_id, product_sale_type','numerical', 'integerOnly'=>true),
			array('title, phone, price, language', 'length', 'max'=>45),
			array('description, specifications', 'safe'),
			array('product_id, title, phone, municipality_id, county_id, description, price, category_id, product_sale_type', 'safe', 'on'=>'search'),
		);
	}

	public function relations()
	{
		return array(
			'variations' => array(self::HAS_MANY, 'ProductVariation', 'product_id', 'order' => 'position'),
			'orders' => array(self::MANY_MANY, 'Order', 'ShopProductOrder(order_id, product_id)'),
			'category' => array(self::BELONGS_TO, 'Category', 'category_id'),
                        'area' => array(self::BELONGS_TO, 'Area', 'municipality_id'),//ivan
                        'region' => array(self::BELONGS_TO, 'Region', 'county_id'),
			'tax' => array(self::BELONGS_TO, 'Tax', 'tax_id'),
			'images' => array(self::HAS_MANY, 'Image', 'product_id'),
			'shopping_carts' => array(self::HAS_MANY, 'ShoppingCart', 'product_id'),
		);
	}

	public function getSpecification($spec) {
		$specs = json_decode($this->specifications, true);

		if(isset($specs[$spec]))
			return $specs[$spec];

		return false;
	}

	public function getImage($image = 0, $thumb = false) {
		if(isset($this->images[$image]))
			return Yii::app()->controller->renderPartial('/image/view', array(
				'model' => $this->images[$image],
				'thumb' => $thumb), true); 
	}

	public function getSpecifications() {
		$specs = json_decode($this->specifications, true);
		return $specs === null ? array() : $specs;
	}

	public function setSpecification($spec, $value) {
		$specs = json_decode($this->specifications, true);

		$specs[$spec] = $value;

		return $this->specifications = json_encode($specs);
	}

	public function setSpecifications($specs) {
		foreach($specs as $k => $v)
			$this->setSpecification($k, $v);
	}

	public function setVariations($variations) {
		$db = Yii::app()->db;
		$db->createCommand()->delete('shop_product_variation',
				'product_id = :product_id', array(
					':product_id' => $this->product_id));

		foreach($variations as $key => $value) {
			if($value['specification_id'] 
					&& isset($value['title']) 
					&& $value['title'] != '') {

				if(isset($value['sign']) && $value['sign'] == '-')
					$value['price_adjustion'] -= 2 * $value['price_adjustion'];


				$db->createCommand()->insert('shop_product_variation', array(
							'product_id' => $this->product_id,
							'specification_id' => $value['specification_id'],
							'position' => @$value['position'] ?: 0,
							'title' => $value['title'],
							'price_adjustion' => @$value['price_adjustion'] ?: 0,
							));	
			}
		}
	}

		public function getVariations() {
		$variations = array();
		foreach($this->variations as $variation) {
			$variations[$variation->specification_id][] = $variation;
		}		

		return $variations;
	}


	public function attributeLabels()
	{
		return array(
			'product_id' => Yii::t('ShopModule.shop', 'Product'),
			'title' => Yii::t('ShopModule.shop', 'Title'),
			'description' => Yii::t('ShopModule.shop', 'Description'),
			'price' => Yii::t('ShopModule.shop', 'Price'),
			'category_id' => Yii::t('ShopModule.shop', 'Category'),
                        'phone' => Yii::t('ShopModule.shop', 'Phone'),//ivan
			'county_id' => Yii::t('ShopModule.shop', 'Area'),
			'municipality_id' => Yii::t('ShopModule.shop', 'Region'),
		);
	}

	public function getTaxRate($variations = null, $amount = 1) { 
		if($this->tax) {
			$taxrate = $this->tax->percent;	
			$price = (float) $this->price;
			if($variations)
				foreach($variations as $key => $variation) {
					$price += @ProductVariation::model()->findByPk($variation[0])->price_adjustion;
				}


			(float) $price *= $amount;

			(float) $tax = $price * ($taxrate / 100);

			return $tax;
		}
	}
	public function getPrice($variations = null, $amount = 1) {
		$price = (float) $this->price;
		if($variations)
			foreach($variations as $key => $variation) {
				$price += @ProductVariation::model()->findByPk($variation[0])->price_adjustion;
			}


		(float) $price *= $amount;

		return $price;
	}

	public function search()
	{

		$criteria=new CDbCriteria;

		$criteria->compare('product_id',$this->product_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('price',$this->price,true);
		$criteria->compare('category_id',$this->category_id);
                $criteria->compare('phone',$this->phone,true);//ivan
		$criteria->compare('county_id',$this->county_id,true);
		$criteria->compare('municipality_id',$this->municipality_id);
                $criteria->compare('product_sale_type',$this->product_sale_type);                
		return new CActiveDataProvider('Products', array(
			'criteria'=>$criteria,
		));
	}
        //ivan
        public function adminSearch()
	{
                $criteria=new CDbCriteria;

		$criteria->compare('product_id',$this->product_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('price',$this->price,true);
		$criteria->compare('category_id',$this->category_id);
                $criteria->compare('phone',$this->phone,true);//ivan
		$criteria->compare('county_id',$this->county_id,true);
		$criteria->compare('municipality_id',$this->municipality_id);
                $criteria->compare('product_sale_type',$this->product_sale_type);  
                if(!(Yii::app()->user->isSuperAdmin() && Yii::app()->user->isPostModerator()))
                    //$criteria->compare('user_id',Yii::app()->user->id);
                    $criteria->compare('user_id',0);
                
		return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 30,
                    ),
                ));
	}
        
        public function indexSearch()
	{

		$criteria=new CDbCriteria;

		$criteria->compare('product_id',$this->product_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('price',$this->price,true);
		$criteria->compare('category_id',$this->category_id);
                $criteria->compare('phone',$this->phone,true);//ivan
		$criteria->compare('county_id',$this->county_id,true);
		$criteria->compare('municipality_id',$this->municipality_id);
                $criteria->compare('product_sale_type',$this->product_sale_type);  
                $orderCondition = 'visitor_count DESC';
                if(isset($_GET['Products']))
                {
                    if($_GET['Products']['orderID']=='1')
                        $orderCondition = 'update_at ASC';
                    if($_GET['Products']['orderID']=='2')
                        $orderCondition = 'price ASC';        
                }
                $criteria->order=$orderCondition;
                
		return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
	}
        //ivan
        public function categorySearch($catID)
	{   
                $this->category_id = $catID;
                $orderCondition = 'visitor_count DESC';
		$criteria=new CDbCriteria;

		$criteria->compare('product_id',$this->product_id);
		$criteria->compare('title',$this->title,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('price',$this->price,true);
		$criteria->compare('category_id',$this->category_id);
                $criteria->compare('phone',$this->phone,true);//ivan
		$criteria->compare('county_id',$this->county_id,true);
		$criteria->compare('municipality_id',$this->municipality_id);
                $criteria->compare('product_sale_type',$this->product_sale_type);  
                $criteria->order=$orderCondition;
                
		return new CActiveDataProvider(get_class($this), array(
                    'criteria' => $criteria,
                    'pagination' => array(
                        'pageSize' => 20,
                    ),
                ));
	}
        public function getOrderOptions(){
                return array(
                    '0' => 'Hotness',
                    '1' => 'Newest',
                    '2' => 'Cheapest'                    
                    );
        }
        public function productSaleType(){
                return array(
                    '0' => Yii::t('ShopModule.shop', 'For Sale'),
                    '1' => Yii::t('ShopModule.shop', 'Rent'),
                    '2' => Yii::t('ShopModule.shop', 'Bytes'),
                    '3' => Yii::t('ShopModule.shop', 'Wish rent'),
                    '4' => Yii::t('ShopModule.shop', 'The purchase'),
                    );
        }
        
}
